package com.vclee.fast.utils.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.vclee.fast.utils.model.Bson;
import com.vclee.fast.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理器
 */
@RestControllerAdvice
public class RRExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(RRException.class)
    public R handleRRException(RRException e) {
        R r = new R();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        HttpServletRequest request = JwtUtils.getContextHttpServletRequest();
        if(request!=null){
            Object info = request.getAttribute("logRsqInfo");
            if(info!=null){
                logger.error("===> HTTP自定义错误:"+ Bson.toString(info)+",响应结果:"+Bson.toString(r));
                request.removeAttribute("info");
            }else {
                logger.error("===> 其他自定义错误:"+e.getMessage(),e);
            }
        }else{
            logger.error("===> 服务自定义异常:"+e.getMessage(),e);
        }
        return r;
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        HttpServletRequest request = JwtUtils.getContextHttpServletRequest();
        if(request!=null){
            Object info = request.getAttribute("logRsqInfo");
            if(info!=null){
                logger.error("===> HTTP服务异常:"+info,e);
                request.removeAttribute("info");
            }else{
                logger.error("===> 其他服务异常:"+e.getMessage(),e);
            }
        }else{
            logger.error("===> 未知服务异常:"+e.getMessage(),e);
        }
        return R.error("未知异常，请联系管理员");
    }
}

